package apis

import (
	"k8sdev/pkg/services"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

func Informer(c *gin.Context) {
	var (
		stopCh     <-chan struct{}
		namespaces []string
		group      string
		version    string
		resources  string
		gvr        schema.GroupVersionResource
	)

	group = c.Param("group")
	version = c.Param("version")
	resources = c.Param("resources")
	gvr = schema.GroupVersionResource{
		Group:    group,
		Version:  version,
		Resource: resources,
	}

	err := services.NewSIF(stopCh)
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	sif := services.GetSif()
	// 获取namespaces
	nsItems, err := sif.Core().V1().Namespaces().Lister().List(labels.Everything())
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	for _, v := range nsItems {
		namespaces = append(namespaces, v.Name)
	}
	// 根据URL动态获取资源
	i, err := sif.ForResource(gvr)
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	items, err := i.Lister().List(labels.Everything())
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"namespaces": namespaces,
		"data":       items,
	})
}
